 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=168 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Render table cells
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='Renderer,RenderPrice,RenderRedGreen,RenderStockName,swing,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Render table cells</div>

<div class='main-body'>
 
<br>Renderers customize how data is presented. For example, one may customize
the rendering of table cells, table column headers, or tree nodes. (IBM
has published an excellent <a href="http://www-106.ibm.com/developerworks/java/library/j-jtable/">article</a>
on table renderers and editors.)
<p>To render table cells as desired, first ensure that the table model
implements <tt><a href="http://java.sun.com/javase/6/docs/api/javax/swing/table/TableModel.html#getColumnClass(int)">getColumnClass</a></tt>.
This will ensure Swing selects the most appropriate default renderer for
each column.
<p>If the default renderer is inadequate, then an implementation of <tt><a href="http://java.sun.com/javase/6/docs/api/javax/swing/table/TableCellRenderer.html">TableCellRenderer</a></tt>
(which has only one method - <tt>getTableCellRendererComponent</tt>) must
be defined, in one of two ways :
<ul>
<li>
subclass <tt><a href="http://java.sun.com/javase/6/docs/api/javax/swing/table/DefaultTableCellRenderer.html">DefaultTableCellRenderer</a></tt>
and override some methods - usually <tt>setValue</tt> or <tt>getTableCellRendererComponent</tt>
(suitable when rendering is similar to <tt>JLabel</tt>)</li>

<li>
implement the interface directly by subclassing a component and adding
an implementation of <tt>getTableCellRendererComponent</tt> (suitable when
rendering is not similar to <tt>JLabel</tt>)</li>
</ul>
It is important to note that <tt>getTableCellRendererComponent</tt> :
<ul>
<li>
usually returns a reference to itself</li>

<li>
should not create a new object each time it is called, for performance
reasons ;&nbsp; the intent is that a single renderer object is reused for
all the cells in a particular column</li>
</ul>
<b>Example 1</b>
<p>The default action of <tt>setValue</tt> is to place the result of <tt>toString</tt>
into a cell. This value may not be appropriate.
<p>Here, <tt>Stock.toString</tt> would place unwanted data in the cell.
The <tt>setValue</tt> method is overridden to customize both the text placed
in a cell, and its associated tooltip :
<br>
<PRE>

<span class='keyword'>package</span> hirondelle.stocks.table;

<span class='keyword'>import</span> javax.swing.table.*;
<span class='keyword'>import</span> hirondelle.stocks.quotes.Stock;
<span class='keyword'>import</span> hirondelle.stocks.util.Util;

<span class='comment'>/**
* Display a {@link Stock} in a table cell by placing the
* full name in the cell, and by providing its Yahoo ticker 
* (including suffix for the {@link hirondelle.stocks.quotes.Exchange}) as tooltip.
*/</span>
<span class='keyword'>final</span> <span class='keyword'>class</span> RenderStockName <span class='keyword'>extends</span> DefaultTableCellRenderer {
  
  <span class='keyword'>public</span> <span class='keyword'>void</span> setValue(Object aValue) {
    Object result = aValue;
    <span class='keyword'>if</span> ( (aValue != <span class='keyword'>null</span>) &amp;&amp; (aValue <span class='keyword'>instanceof</span> Stock) ) {
      Stock stock = (Stock) aValue;
      result = stock.getName();
      StringBuilder tooltip = <span class='keyword'>new</span> StringBuilder(<span class='literal'>"Yahoo Ticker: "</span>);
      tooltip.append(stock.getTicker());
      String suffix = stock.getExchange().getTickerSuffix();
      <span class='keyword'>if</span> ( Util.textHasContent(suffix) ) {
        tooltip.append(<span class='literal'>"."</span>);
        tooltip.append(suffix);
      }
      setToolTipText( tooltip.toString() );
    } 
    <span class='keyword'>super</span>.setValue(result);
  }   
} 
</PRE>
<br>
<br><b>Example 2</b>
<p>Use the current locale to render a <tt>Number</tt> as a currency :
<br>
<PRE>

<span class='keyword'>package</span> hirondelle.stocks.table;

<span class='keyword'>import</span> javax.swing.table.*;
<span class='keyword'>import</span> javax.swing.*;
<span class='keyword'>import</span> java.text.NumberFormat;

<span class='comment'>/**
* Display a &lt;tt&gt;Number&lt;/tt&gt; in a table cell in the format defined by  
* {@link NumberFormat#getCurrencyInstance()}, and aligned to the right.
*/</span>
<span class='keyword'>final</span> <span class='keyword'>class</span> RenderPrice <span class='keyword'>extends</span> DefaultTableCellRenderer {
  
  RenderPrice() { 
    setHorizontalAlignment(SwingConstants.RIGHT);  
  }
  
  <span class='keyword'>public</span> <span class='keyword'>void</span> setValue(Object aValue) {
    Object result = aValue;
    <span class='keyword'>if</span> (( aValue != <span class='keyword'>null</span>) &amp;&amp; (aValue <span class='keyword'>instanceof</span> Number)) {
      Number numberValue = (Number)aValue;
      NumberFormat formatter = NumberFormat.getCurrencyInstance();
      result = formatter.format(numberValue.doubleValue());
    } 
    <span class='keyword'>super</span>.setValue(result);
  }   
} 
</PRE>
<br>
<br><b>Example 3</b>
<p>Render as red or green, according to the sign of a <tt>Number</tt>.
The implementation overrides <tt>getTableCellRendererComponent</tt> instead
of <tt>setValue</tt>, and returns a <tt>this</tt> reference.
<br>
<PRE>

<span class='keyword'>package</span> hirondelle.stocks.table;

<span class='keyword'>import</span> javax.swing.table.*;
<span class='keyword'>import</span> javax.swing.*;
<span class='keyword'>import</span> java.awt.*;

<span class='comment'>/**
* Display a &lt;tt&gt;Number&lt;/tt&gt; in a table cell as either red (for negative values)
* or green (for non-negative values), and aligned on the right.
*
* &lt;P&gt;Note that this class will work with any &lt;tt&gt;Number&lt;/tt&gt; -  
* &lt;tt&gt;Double&lt;/tt&gt;, &lt;tt&gt;BigDecimal&lt;/tt&gt;, etc.
*/</span>
<span class='keyword'>final</span> <span class='keyword'>class</span> RenderRedGreen <span class='keyword'>extends</span> DefaultTableCellRenderer {
  
  RenderRedGreen () {
    setHorizontalAlignment(SwingConstants.RIGHT);   
  }
  
  <span class='keyword'>public</span> Component getTableCellRendererComponent(
    JTable aTable, 
    Object aNumberValue, 
    <span class='keyword'>boolean</span> aIsSelected, 
    <span class='keyword'>boolean</span> aHasFocus, 
    <span class='keyword'>int</span> aRow, <span class='keyword'>int</span> aColumn
  ) {  
    <span class='comment'>/* 
    * Implementation Note :
    * It is important that no "new" be present in this 
    * implementation (excluding exceptions):
    * if the table is large, then a large number of objects would be 
    * created during rendering.
    */</span>
    <span class='keyword'>if</span> (aNumberValue == <span class='keyword'>null</span>) <span class='keyword'>return</span> <span class='keyword'>this</span>;
    Component renderer = <span class='keyword'>super</span>.getTableCellRendererComponent(
      aTable, aNumberValue, aIsSelected, aHasFocus, aRow, aColumn
    );
    Number value = (Number)aNumberValue;
    <span class='keyword'>if</span> ( value.doubleValue() &lt; <span class='literal'>0</span> ) {
      renderer.setForeground(Color.red);
    }
    <span class='keyword'>else</span> {
      renderer.setForeground(fDarkGreen);
    }
    <span class='keyword'>return</span> <span class='keyword'>this</span>;
  }
  
  <span class='comment'>// PRIVATE //
</span>  
  <span class='comment'>//(The default green is too bright and illegible.)
</span>  <span class='keyword'>private</span> Color fDarkGreen = Color.green.darker();
} 
</PRE>
<br>
<p>Here is an illustration of all three example renderers :
<p><IMG SRC="../images/Renderers.gif" ALT="Illustration of above renderers" height=317 width=582 border=0>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction789c-2.html?Id=161'>Indicate table sort</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='168'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=168 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
